<template>
  <div class="assessment-report">
    <div class="page-header">
      <h3>查询报告入口</h3>
      <p>查看和下载团队测评报告</p>
    </div>

    <div class="report-container">
      <div class="search-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="团队名称">
            <el-input v-model="searchForm.teamName" placeholder="请输入团队名称" clearable />
          </el-form-item>
          <el-form-item label="报告类型">
            <el-select v-model="searchForm.reportType" placeholder="请选择报告类型" clearable style="width: 150px">
              <el-option label="个人报告" value="个人报告" />
              <el-option label="团队报告" value="团队报告" />
              <el-option label="综合报告" value="综合报告" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="report-table">
        <el-table :data="reportData" style="width: 100%" v-loading="loading">
          <el-table-column prop="teamName" label="团队名称"   />
          <el-table-column prop="reportType" label="报告类型" width="120">
            <template #default="scope">
              <el-tag :type="getReportTypeColor(scope.row.reportType)">
                {{ scope.row.reportType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assessmentType" label="测评类型"   />
          <el-table-column prop="participantCount" label="参与人数" width="100" align="center" />
          <el-table-column prop="completionRate" label="完成率" width="100" align="center">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.completionRate"
                :stroke-width="8"
                :color="getProgressColor(scope.row.completionRate)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="generateTime" label="生成时间"   />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusColor(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="300">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleViewReport(scope.row)"
                :disabled="scope.row.status !== '已完成'"
              >
                查看报告
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleDownloadReport(scope.row)"
                :disabled="scope.row.status !== '已完成'"
              >
                下载PDF
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleShareReport(scope.row)"
                :disabled="scope.row.status !== '已完成'"
              >
                分享
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteReport(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 报告预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="报告预览" width="80%" top="5vh">
      <div v-if="selectedReport" class="report-preview">
        <div class="report-header">
          <h2>{{ selectedReport.teamName }} - {{ selectedReport.reportType }}</h2>
          <div class="report-meta">
            <span>测评类型：{{ selectedReport.assessmentType }}</span>
            <span>生成时间：{{ selectedReport.generateTime }}</span>
            <span>参与人数：{{ selectedReport.participantCount }}人</span>
          </div>
        </div>

        <div class="report-content">
          <div class="summary-section">
            <h3>测评概览</h3>
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-number">{{ selectedReport.participantCount }}</div>
                  <div class="stat-label">参与人数</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-number">{{ selectedReport.completionRate }}%</div>
                  <div class="stat-label">完成率</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-number">{{ selectedReport.avgScore || 85 }}</div>
                  <div class="stat-label">平均分</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-card">
                  <div class="stat-number">A</div>
                  <div class="stat-label">团队等级</div>
                </div>
              </el-col>
            </el-row>
          </div>

          <div class="chart-section">
            <h3>能力分布</h3>
            <div class="charts-container">
              <div class="chart-item">
                <h4>角色分布</h4>
                <div class="chart-placeholder">
                  <el-progress
                    type="circle"
                    :percentage="75"
                    :width="120"
                    stroke-width="8"
                  >
                    <span class="chart-label">领导者</span>
                  </el-progress>
                  <el-progress
                    type="circle"
                    :percentage="85"
                    :width="120"
                    stroke-width="8"
                    color="#67c23a"
                  >
                    <span class="chart-label">协作者</span>
                  </el-progress>
                  <el-progress
                    type="circle"
                    :percentage="60"
                    :width="120"
                    stroke-width="8"
                    color="#e6a23c"
                  >
                    <span class="chart-label">创新者</span>
                  </el-progress>
                </div>
              </div>
            </div>
          </div>

          <div class="analysis-section">
            <h3>分析报告</h3>
            <div class="analysis-content">
              <p><strong>团队优势：</strong></p>
              <ul>
                <li>团队协作能力突出，成员间配合默契</li>
                <li>技术能力强，能够快速解决复杂问题</li>
                <li>学习能力强，适应性好</li>
              </ul>

              <p><strong>改进建议：</strong></p>
              <ul>
                <li>加强创新思维培养，提升团队创新能力</li>
                <li>完善沟通机制，提高信息传递效率</li>
                <li>建立更完善的知识分享体系</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownloadFromPreview">下载报告</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享报告" width="500px">
      <div class="share-content">
        <div class="share-methods">
          <h4>分享方式</h4>
          <el-radio-group v-model="shareMethod">
            <el-radio label="link">生成分享链接</el-radio>
            <el-radio label="email">邮件发送</el-radio>
          </el-radio-group>
        </div>

        <div v-if="shareMethod === 'link'" class="share-link">
          <h4>分享链接</h4>
          <el-input
            v-model="shareLink"
            readonly
            class="share-input"
          >
            <template #append>
              <el-button @click="handleCopyLink">复制</el-button>
            </template>
          </el-input>
          <p class="share-tip">链接有效期：7天</p>
        </div>

        <div v-if="shareMethod === 'email'" class="share-email">
          <h4>邮件发送</h4>
          <el-form :model="emailForm" label-width="80px">
            <el-form-item label="收件人">
              <el-input v-model="emailForm.recipients" placeholder="请输入邮箱地址，多个地址用逗号分隔" />
            </el-form-item>
            <el-form-item label="主题">
              <el-input v-model="emailForm.subject" placeholder="邮件主题" />
            </el-form-item>
            <el-form-item label="内容">
              <el-input v-model="emailForm.content" type="textarea" rows="4" placeholder="邮件内容" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmShare">确定分享</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const previewDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const selectedReport = ref(null)
const shareMethod = ref('link')
const shareLink = ref('https://example.com/report/share/abc123')

// 搜索表单
const searchForm = reactive({
  teamName: '',
  reportType: '',
  dateRange: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 邮件表单
const emailForm = reactive({
  recipients: '',
  subject: '',
  content: ''
})

// 报告数据
const reportData = ref([
  {
    id: 1,
    teamName: '产品研发团队',
    reportType: '团队报告',
    assessmentType: '团队角色评估',
    participantCount: 8,
    completionRate: 100,
    generateTime: '2024-08-13 14:30:00',
    status: '已完成'
  },
  {
    id: 2,
    teamName: '市场营销团队',
    reportType: '个人报告',
    assessmentType: '领导力评估',
    participantCount: 6,
    completionRate: 85,
    generateTime: '2024-08-12 16:20:00',
    status: '已完成'
  },
  {
    id: 3,
    teamName: '技术支持团队',
    reportType: '综合报告',
    assessmentType: '团队协作评估',
    participantCount: 12,
    completionRate: 75,
    generateTime: '2024-08-11 10:15:00',
    status: '生成中'
  },
  {
    id: 4,
    teamName: '人力资源团队',
    reportType: '团队报告',
    assessmentType: '综合能力评估',
    participantCount: 5,
    completionRate: 100,
    generateTime: '2024-08-10 09:30:00',
    status: '已完成'
  }
])

// 方法
const getReportTypeColor = (type) => {
  const colorMap = {
    '个人报告': 'primary',
    '团队报告': 'success',
    '综合报告': 'warning'
  }
  return colorMap[type] || 'info'
}

const getStatusColor = (status) => {
  const colorMap = {
    '已完成': 'success',
    '生成中': 'warning',
    '失败': 'danger'
  }
  return colorMap[status] || 'info'
}

const getProgressColor = (percentage) => {
  if (percentage === 100) return '#67c23a'
  if (percentage >= 80) return '#409eff'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
}

const handleSearch = () => {
  loading.value = true
  setTimeout(() => {
    ElMessage.success('搜索完成')
    loading.value = false
  }, 1000)
}

const handleReset = () => {
  Object.assign(searchForm, {
    teamName: '',
    reportType: '',
    dateRange: null
  })
  handleSearch()
}

const handleViewReport = (row) => {
  selectedReport.value = row
  previewDialogVisible.value = true
}

const handleDownloadReport = (row) => {
  ElMessage.success(`正在下载${row.teamName}的报告...`)
  // 模拟下载
  setTimeout(() => {
    ElMessage.success('下载完成')
  }, 2000)
}

const handleDownloadFromPreview = () => {
  if (selectedReport.value) {
    handleDownloadReport(selectedReport.value)
  }
}

const handleShareReport = (row) => {
  selectedReport.value = row
  shareDialogVisible.value = true
  // 重置分享表单
  shareMethod.value = 'link'
  Object.assign(emailForm, {
    recipients: '',
    subject: `${row.teamName} - ${row.reportType}`,
    content: `请查看附件中的测评报告。\n\n团队：${row.teamName}\n类型：${row.reportType}\n生成时间：${row.generateTime}`
  })
}

const handleCopyLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败，请手动复制')
  }
}

const handleConfirmShare = () => {
  if (shareMethod.value === 'link') {
    ElMessage.success('分享链接已生成')
  } else if (shareMethod.value === 'email') {
    if (!emailForm.recipients) {
      ElMessage.warning('请输入收件人邮箱')
      return
    }
    ElMessage.success('邮件发送成功')
  }
  shareDialogVisible.value = false
}

const handleDeleteReport = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${row.teamName}"的报告吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const index = reportData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      reportData.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadReportData()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadReportData()
}

const loadReportData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = reportData.value.length
    loading.value = false
  }, 500)
}

onMounted(() => {
  loadReportData()
})
</script>

<style scoped>
.assessment-report {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.page-header h3 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.search-bar {
  background: #f8fafc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.report-table {
  background: white;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.report-preview {
  max-height: 70vh;
  overflow-y: auto;
}

.report-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e5e7eb;
}

.report-header h2 {
  margin: 0 0 10px 0;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
}

.report-meta {
  display: flex;
  justify-content: center;
  gap: 30px;
  color: #6b7280;
  font-size: 14px;
}

.report-content {
  padding: 0 20px;
}

.summary-section,
.chart-section,
.analysis-section {
  margin-bottom: 30px;
}

.summary-section h3,
.chart-section h3,
.analysis-section h3 {
  margin: 0 0 20px 0;
  color: #1f2937;
  font-size: 18px;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #5a67d8;
  margin-bottom: 8px;
}

.stat-label {
  color: #6b7280;
  font-size: 14px;
}

.chart-item {
  text-align: center;
}

.chart-item h4 {
  margin: 0 0 20px 0;
  color: #374151;
  font-size: 16px;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  gap: 30px;
  align-items: center;
}

.chart-label {
  font-size: 12px;
  color: #374151;
}

.analysis-content {
  line-height: 1.8;
  color: #374151;
}

.analysis-content p {
  margin: 0 0 15px 0;
}

.analysis-content ul {
  margin: 0 0 20px 20px;
  padding: 0;
}

.analysis-content li {
  margin-bottom: 8px;
}

.share-content {
  padding: 10px 0;
}

.share-methods h4,
.share-link h4,
.share-email h4 {
  margin: 0 0 15px 0;
  color: #374151;
  font-size: 16px;
  font-weight: 600;
}

.share-input {
  margin-bottom: 10px;
}

.share-tip {
  margin: 0;
  color: #6b7280;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-progress-bar__outer) {
  border-radius: 10px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 10px;
}
</style>
